<template>
	<div class="account">
		<div class="header">
			<div class="label-wrapper">
				<p class="label">账号管理</p>
				<p class="line"></p>
			</div>
			<div class="btns">
				<el-button class="account-button" @click="importAgents">导入账号</el-button>
				<el-button class="account-button" @click="addAgent">新增账号</el-button>
			</div>
		</div>
		<div class="table" v-show="isOrgAdmin">
			<Table :tableData="agentData">
				<template v-slot:btn>
					<el-table-column width="700px" align="center" label="操作">
						<template slot-scope="scope">
							<!-- 删除remove | 失效invalid | 设置角色role | 绑定分组bind | 重置密码 password | 编辑属性 property -->
							<!-- 机器人角色对应账户在操作栏中“改变角色”以及“重置密码按钮隐藏，机构管理员仅保留重置密码操作。 -->
							<el-button v-show="!['机构管理员', 'admin'].includes(scope.row.role)" size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
							<span class="stop-enable-blue">
								<el-button v-show="!['机构管理员', 'admin'].includes(scope.row.role)" size="mini" @click="stopEnableAgent(scope.$index, scope.row, $event)">{{
									scope.row.status === 'N' ? '停用' : '启用'
								}}</el-button>
							</span>
							<el-button
								v-show="!scope.row.isRobot && (scope.row.createdBy == selfUserId || scope.row.userId == selfUserId) && scope.row.isInitPwd === 'Y'"
								size="mini"
								class="blue"
								@click="showPwdView(scope.$index, scope.row)"
								:disabled="scope.row.resetPwd"
								>初始密码</el-button
							>
							<!-- <el-button v-show="!scope.row.isRobot" size="mini" class="blue" @click="resetPwd(scope.$index, scope.row)" :disabled="scope.row.resetPwd">重置密码</el-button> -->
							<el-button v-show="!scope.row.isRobot && !['机构管理员', 'admin', '管理员'].includes(scope.row.role)" size="mini" class="blue" @click="changeRole(scope.$index, scope.row)"
								>改变角色</el-button
							>
							<el-button v-show="!scope.row.isRobot && !['机构管理员', 'admin'].includes(scope.row.role)" size="mini" class="blue" @click="changeName(scope.$index, scope.row)"
								>修改姓名</el-button
							>
							<!-- 绑定分组和编辑属性仅在当前账户绑定了勾选工作台权限的角色才显示 -->
							<el-button
								v-show="scope.row.permission.includes(1) && !['机构管理员', 'admin'].includes(scope.row.role)"
								size="mini"
								class="blue"
								@click="viewshowBindGroup(scope.$index, scope.row)"
								>绑定分组</el-button
							>
							<el-button v-show="scope.row.permission.includes(1) && !['机构管理员', 'admin'].includes(scope.row.role)" size="mini" class="blue" @click="onShowBindLabelDialog(scope.row)"
								>绑定标签</el-button
							>
							<el-button
								v-show="scope.row.permission.includes(1) && !['机构管理员', 'admin'].includes(scope.row.role)"
								size="mini"
								class="blue"
								@click="editProperty(scope.$index, scope.row)"
								>编辑属性</el-button
							>
							<div v-show="!scope.row.isRobot && scope.row.userId == selfUserId && scope.row.isInitPwd === 'N'" size="mini">-</div>
							<el-button
								v-show="scope.row.isLockedByPasswordError === 'Y' && !['机构管理员'].includes(scope.row.role)"
								size="mini"
								class="blue"
								@click="unlockAccount(scope.$index, scope.row)"
								>解锁账号</el-button
							>
						</template>
					</el-table-column>
				</template>
			</Table>
		</div>
		<div class="table" v-show="!isOrgAdmin">
			<Table :tableData="agentData">
				<template v-slot:btn>
					<el-table-column width="700px" align="center" label="操作">
						<template slot-scope="scope">
							<!-- 删除remove | 失效invalid | 设置角色role | 绑定分组bind | 重置密码 password | 编辑属性 property -->
							<!-- 机器人角色对应账户在操作栏中“改变角色”以及“重置密码按钮隐藏，机构管理员仅保留重置密码操作。 -->
							<el-button v-show="scope.row.originRole === 'agent'" size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
							<span class="stop-enable-blue">
								<el-button v-show="scope.row.originRole === 'agent'" size="mini" @click="stopEnableAgent(scope.$index, scope.row, $event)">{{
									scope.row.status === 'N' ? '停用' : '启用'
								}}</el-button>
							</span>
							<el-button
								v-show="!scope.row.isRobot && (scope.row.createdBy == selfUserId || scope.row.userId == selfUserId) && scope.row.isInitPwd === 'Y'"
								size="mini"
								class="blue"
								@click="showPwdView(scope.$index, scope.row)"
								:disabled="scope.row.resetPwd"
								>初始密码</el-button
							>
							<!-- <el-button
								v-show="(scope.row.originRole === 'agent' || selfUserId == scope.row.userId) && !scope.row.isRobot"
								size="mini"
								class="blue"
								@click="resetPwd(scope.$index, scope.row)"
								:disabled="scope.row.resetPwd"
								>重置密码</el-button
							> -->
							<el-button v-show="scope.row.originRole === 'agent' && !scope.row.isRobot" size="mini" class="blue" @click="changeRole(scope.$index, scope.row)">改变角色</el-button>
							<el-button v-show="scope.row.originRole === 'agent' && !scope.row.isRobot" size="mini" class="blue" @click="changeName(scope.$index, scope.row)">修改姓名</el-button>
							<!-- 绑定分组和编辑属性仅在当前账户绑定了勾选工作台权限的角色才显示 -->
							<el-button v-show="scope.row.originRole === 'agent'" size="mini" class="blue" @click="viewshowBindGroup(scope.$index, scope.row)">绑定分组</el-button>
							<el-button v-show="scope.row.originRole === 'agent'" size="mini" class="blue" @click="onShowBindLabelDialog(scope.row)">绑定标签</el-button>
							<el-button v-show="scope.row.originRole === 'agent'" size="mini" class="blue" @click="editProperty(scope.$index, scope.row)">编辑属性</el-button>
							<div v-show="!scope.row.isRobot && scope.row.isInitPwd === 'N' && (scope.row.userId == selfUserId || ['机构管理员', '管理员'].includes(scope.row.role))" size="mini">-</div>
							<!-- 只有管理员角色（机构管理员、管理员）有解锁权限，且同级无法进行解锁。机构管理员账号被锁定需要超管进行解锁；管理员和座席账号被锁定，机构管理员可以进行解锁；座席账号被锁定，机构管理员和管理员可以进行解锁 -->
							<el-button
								v-show="scope.row.originRole === 'agent' && scope.row.isLockedByPasswordError === 'Y' && !['机构管理员'].includes(scope.row.role)"
								size="mini"
								class="blue"
								@click="unlockAccount(scope.$index, scope.row)"
								>解锁账号</el-button
							>
						</template>
					</el-table-column>
				</template>
			</Table>
		</div>
		<br />
		<div class="page">
			<PageSize :pages="checkAgent" @changePageSize="changeAgentPageSize" @changeCurrentPage="changeAgentCurrentPage" />
		</div>
		<BindGroup
			v-if="showBindGroup"
			:showBindGroup="showBindGroup"
			:tableData="groupsSkill"
			@closeBindGroup="closeBindGroup"
			@addGroup="addGroupSkill"
			@removeGroup="removeGroupSkill"
			@edit="editGroupSkill"
			@save="save"
		>
		</BindGroup>
		<ChangePassword
			v-show="showChangePwd"
			:show="showChangePwd"
			:userId="curAccount.userId"
			@close="
				() => {
					showChangePwd = false;
				}
			"
		/>
		<ImportAgents
			:isOrgAdmin="isOrgAdmin"
			v-show="showImportAgents"
			:show="showImportAgents"
			:roleList="roles.filter(item => item.canSelect)"
			@close="
				() => {
					showImportAgents = false;
				}
			"
			@importAccountsSuccess="
				() => {
					this.getAgentListInit();
					this.showImportAgents = false;
				}
			"
		/>
		<CreateAccount
			v-show="showAddAgent"
			:show="showAddAgent"
			:roleList="roles.filter(item => item.canSelect)"
			@close="
				() => {
					showAddAgent = false;
				}
			"
			@create="onAccountCreated"
		/>
		<ModifyAgentRealName
			v-show="showChangeName"
			:show="showChangeName"
			:account="curAccount"
			@modifyUserFullNameSuccess="
				fullName => {
					this.curAccount.fullName = fullName;
					this.showChangeName = false;
				}
			"
			@close="
				() => {
					showChangeName = false;
				}
			"
		/>
		<!-- 修改角色中屏蔽“机构管理员”“机器人坐席” "管理员" 角色 -->
		<ChangeRole
			v-show="showChangeRole"
			:show="showChangeRole"
			:userId="curAccount.userId"
			:role="curAccount"
			:roleList="roles.filter(item => item.canSelect && item.name !== '机器人坐席' && item.name !== '管理员')"
			@close="
				() => {
					showChangeRole = false;
				}
			"
			@change="onChangeRole"
		/>
		<CheckGroupInfo
			:attributes="schedulingAttributes"
			:show="showModifyProp"
			:acount="curAccount"
			@close="
				() => {
					showModifyProp = false;
				}
			"
			@update="updateAttributes"
		>
			<!-- <template v-slot:page>
				<el-pagination
					@size-change="changeGroupPageSize"
					@current-change="changeGroupCurrentPage"
					:current-page="checkGroup.page"
					:page-sizes="[10, 20, 30, 40]"
					:page-size="checkGroup.pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="checkGroup.total"
				>
				</el-pagination>
			</template> -->
		</CheckGroupInfo>
		<bind-label v-if="showBindLabel" @close="onCloseBindLabelDialog" :accountData="willBindBizLabelUserData"></bind-label>
		<el-dialog title="温馨提示" :visible.sync="copyPwdDialogVisible" width="50%" append-to-body="true">
			<span>密码:{{ dialogPassword }}</span>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="copyPassword">复制</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import Table from '../../components/Table.vue';
import PageSize from '../../components/PageSize.vue';
import BindGroup from './BindGroup.vue';
import ChangePassword from './ChangePassword.vue';
import ImportAgents from '@/views/AccountPermissions/Manament/ImportAgents.vue';
import CreateAccount from './CreateAccount.vue';
import ModifyAgentRealName from '@/views/AccountPermissions/Manament/ModifyAgentRealName.vue';
import ChangeRole from './ChangeRole.vue';
import CheckGroupInfo from './CheckGroupInfo.vue';
import BindLabel from './BindLabel.vue';

import { isServing, getUserList, deleteAccount, updateAccountInfo, getAllGroups, getGroupWithUserId, saveGroupPriority, getRoleList, checkWorkbench, unlock } from '../../../api/api';

import { validatePass, validatePassChecked } from '@/utils/formValidate';
import { mapState } from 'vuex';
export default {
	components: {
		Table,
		PageSize,
		BindGroup,
		ChangePassword,
		ImportAgents,
		CreateAccount,
		ModifyAgentRealName,
		ChangeRole,
		CheckGroupInfo,
		BindLabel
	},
	data() {
		return {
			dialogPassword: '', // 被查看的密码
			copyPwdDialogVisible: false, // 查看初始密码弹框
			activeName: 'agent',
			willBindBizLabelUserData: undefined,
			checkAgent: {
				page: 1,
				pageSize: 10,
				total: 0,
				role: 'agent'
			},
			userInfo: {
				userId: '',
				pass: '',
				checkPass: ''
			},
			checkGroup: {
				page: 1,
				pageSize: 10,
				total: 0,
				userId: ''
			},
			pwdRules: {
				pass: [
					{ required: true, message: '请输入用户密码', trigger: ['blur', 'change'] },
					{ validator: validatePass, trigger: ['blur', 'change'] }
				],
				checkPass: [
					{ required: true, message: '请输入用户密码', trigger: ['blur', 'change'] },
					{ validator: validatePassChecked, trigger: ['blur', 'change'] }
				]
			},
			showChangePwd: false,
			showImportAgents: false,
			showAddAgent: false,
			showChangeRole: false,
			showChangeName: false,
			showModifyProp: false,

			agentData: {
				sort: false,
				tableHead: [
					{
						label: '用户名',
						prop: 'userName'
					},
					{
						label: '角色',
						prop: 'role'
					},
					{
						label: '姓名',
						prop: 'fullName'
					},
					{
						label: '账号创建时间',
						prop: 'createdAt',
						width: '120px'
					},
					{
						label: '账户状态',
						prop: 'isDisabled'
					}
				],
				tableConent: [],
				showIndex: false
			},

			groupList: [],

			showBindGroup: false,
			// 并发分组
			groupsSkill: {
				showNo: false,
				showCheck: false,
				isEdit: true,
				tableHead: [
					{
						label: '技能组名称',
						prop: 'name'
					},
					{
						label: '组内权重',
						prop: 'weight'
					},
					{
						label: '多组并发权重',
						prop: 'groupPriority'
					},
					{
						label: '是否组长',
						prop: 'isChief'
					}
				],
				tableConent: [],
				options: [
					{
						value: '10',
						label: '技能组1'
					},
					{
						value: '20',
						label: '技能组2'
					},
					{
						value: '30',
						label: '技能组3'
					},
					{
						value: '40',
						label: '技能组4'
					},
					{
						value: '50',
						label: '技能组5'
					}
				]
			},
			// 默认并发组数据
			defaultGroupSkill: {
				name: {
					value: '',
					label: '',
					isSet: true,
					isEmpty: false,
					isRepeats: false
				},
				weight: {
					value: 1,
					isSet: true,
					invalid: false
				},
				isChief: {
					value: false,
					isSet: true,
					invalid: false
				},
				groupPriority: {
					value: 1,
					isSet: true,
					invalid: false
				}
			},
			// 接口返回分组信息，用于筛选 id
			groupsSkillData: [],
			curAccount: {}, // 当前操作的账号
			roles: [], // 角色列表
			showBindLabel: false,
			isOrgAdmin: true, // 是否是机构管理员
			selfUserId: localStorage.getItem(`zco_admin_userId_${window.uid}`),
			userRoleId: localStorage.getItem(`zco_admin_roleId_${window.uid}`)
		};
	},
	computed: {
		...mapState({
			// userRole: state => state.login.userInfo.userRole
		})
	},
	async mounted() {
		console.log('userROle', this.userRoleId);
		await this.getRoleList();
		this.getAgentListInit();
		this.getAllGroupInit();
	},

	methods: {
		unlockAccount(index, row) {
			this.$Spin.show();
			unlock(row.userId)
				.then(res => {
					this.$Spin.hide();
					this.getAgentListInit();
					this.$message({
						type: 'success',
						message: '账号解锁成功!'
					});
				})
				.catch(err => {
					console.error('unlockAccount error ', err);
					this.$Spin.hide();
					this.$requestApiError(err, () => {
						this.$router.push('/');
					});
				});
		},

		showPwdView(index, row) {
			console.log('index, row', index, row);
			this.copyPwdDialogVisible = true;
			this.dialogPassword = row.initPwd;
		},

		copyPassword() {
			console.log('copy password,', this.dialogPassword);
			this.copyPwdDialogVisible = false;
			navigator.clipboard &&
				navigator.clipboard
					.writeText(this.dialogPassword)
					.then(() => {
						this.$message.success('复制成功');
					})
					.catch(() => {
						this.$message.error('复制失败');
					});
		},
		getAllGroupInit() {
			getAllGroups().then(res => {
				this.groupsSkill.options = res.data;
			});
		},
		// 用户数据分页
		changeAgentPageSize(val) {
			this.checkAgent.role = 'agent';
			this.checkAgent.pageSize = val;
			this.checkAgent.page = 1;
			this.getAgentListInit();
		},
		changeAgentCurrentPage(val) {
			this.checkAgent.role = 'agent';
			this.checkAgent.page = val;
			this.getAgentListInit();
		},
		// 批量导入坐席
		importAgents() {
			this.showImportAgents = true;
		},

		// 新增座席
		addAgent() {
			this.showAddAgent = true;
		},

		/**
		 * 判断坐席是否在通话中
		 * @param {int} userId
		 */
		isServing(userId) {
			console.log('isServing user', userId);
			return new Promise((resolve, reject) => {
				isServing(userId)
					.then(resp => {
						console.log('isServingUser data', resp.data);
						if (resp && resp.data && resp.data.code === 200) {
							if (resp.data.data.isServing) {
								resolve(1);
							} else {
								resolve(0);
							}
						} else {
							resolve(0);
						}
					})
					.catch(e => {
						reject(e);
					});
			});
		},

		// 删除用户
		async deleteUser(index, row) {
			console.log('deleteUser user', row, index);
			try {
				const subtitle = row.role === 'agent' ? `确定要删除坐席 <${row.userName}> 吗, 是否继续?` : `确定要删除用户 <${row.userName}> 吗, 是否继续?`;
				// if (row.role === 'agent') {
				this.$Spin.show();
				const isServingUser = await this.isServing(row.userId);
				console.log('isServingUser', isServingUser);
				this.$Spin.hide();
				if (isServingUser) {
					this.$confirm(`确定要删除坐席 <${row.userName}> 吗, 该坐席正在通话中，将会强制结束会话，是否继续?`, '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
						.then(async () => {
							await this.deleteAccount(row.userId);
							this.$message({
								type: 'success',
								message: '删除成功!'
							});
						})
						.catch(() => {
							this.$message({
								type: 'info',
								message: '已取消'
							});
						});
				} else {
					this.$confirm(subtitle, '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
						.then(async () => {
							await this.deleteAccount(row.userId);
							this.$message({
								type: 'success',
								message: '删除成功!'
							});
						})
						.catch(() => {
							this.$message({
								type: 'info',
								message: '已取消'
							});
						});
				}
				// }
			} catch (error) {
				console.error('delete user ', error);
				this.$Spin.hide();
				this.$message.error('删除失败！');
			}
		},

		/**
		 * 根据userId删除账号
		 * @param {int} userId
		 */
		deleteAccount(userId) {
			return new Promise((resolve, reject) => {
				deleteAccount(userId)
					.then(res => {
						if (res.status === 200) {
							this.getAgentListInit();
							resolve('ok');
						}
					})
					.catch(err => {
						reject(err);
					});
			});
		},

		// 重置密码
		resetPwd(index, row) {
			this.curAccount = row;
			this.userInfo.userId = row.userId;
			this.showChangePwd = true;
		},

		// 绑定分组
		async viewshowBindGroup(index, row) {
			try {
				await checkWorkbench(row.userId);
				this.checkGroup.page = 1;
				this.checkGroup.pageSize = 10;
				this.checkGroup.userId = row.userId;
				this.groupsSkill.tableConent = [];
				this.groupsSkill.isEdit = true;
				this.showBindGroup = true;
				this.getGroupWithUserIdInit();
			} catch (error) {
				if (error && error.code === '1105') {
					this.$message.error(`该账户无工作台权限无法进行操作`);
				}
			}
		},
		// 关闭绑定分组对话框
		closeBindGroup() {
			this.groupsSkill.tableConent = [];
			this.showBindGroup = false;
		},
		// 编辑分组,初始化编辑状态
		editGroupSkill() {
			this.groupsSkill.isEdit = false;
			if (this.groupsSkill.tableConent.length === 0) {
				this.groupsSkill.tableConent.push({
					name: {
						value: '',
						label: '',
						isSet: true,
						isEmpty: false,
						isRepeats: false
					},
					weight: {
						value: 1,
						isSet: true,
						invalid: false
					},
					isChief: {
						value: false,
						isSet: true
					},
					groupPriority: {
						value: 1,
						isSet: true,
						invalid: false
					}
				});
			}
			this.groupsSkill.tableConent.forEach(item => {
				item.name.isSet = true;
				item.weight.isSet = true;
				item.isChief.isSet = true;
				item.groupPriority.isSet = true;
			});
		},
		// 保存分组
		save() {
			let submitData = [];
			let repeats = [];
			let flag = false;
			for (let i = 0; i < this.groupsSkill.tableConent.length; i++) {
				let groupId = this.groupsSkill.tableConent[i].name.value;
				let weight = this.groupsSkill.tableConent[i].weight.value;
				let groupPriority = this.groupsSkill.tableConent[i].groupPriority.value;
				// 校验值合法性
				if (groupId === '') {
					this.groupsSkill.tableConent[i].name.isEmpty = true;
					flag = true;
				} else {
					this.groupsSkill.tableConent[i].name.isEmpty = false;
				}
				if (Number(weight) > 99 || Number(weight) < 1 || !new RegExp('^[0-9]+$', 'g').test(weight)) {
					this.groupsSkill.tableConent[i].weight.invalid = true;
					flag = true;
				} else {
					this.groupsSkill.tableConent[i].weight.invalid = false;
				}
				if (Number(groupPriority) > 99 || Number(groupPriority) < 1 || !new RegExp('^[0-9]+$', 'g').test(groupPriority)) {
					this.groupsSkill.tableConent[i].groupPriority.invalid = true;
					flag = true;
				} else {
					this.groupsSkill.tableConent[i].groupPriority.invalid = false;
				}
				// 去重
				if (repeats.indexOf(groupId) !== -1) {
					this.groupsSkill.tableConent[i].name.isRepeats = true;
					this.groupsSkill.tableConent[i].name.isSet = true;
					flag = true;
				} else {
					repeats.push(groupId);
					this.groupsSkill.tableConent[i].name.isRepeats = false;
					if (!flag) {
						let obj = {};
						obj.groupId = groupId;
						obj.name = this.groupsSkill.tableConent[i].name.label;
						obj.isChief = Boolean(this.groupsSkill.tableConent[i].isChief.value);
						obj.weight = Number(weight);
						obj.groupPriority = Number(groupPriority);
						// 取出修改元素 id
						let ids = this.groupsSkillData.filter(item => item.groupId === groupId);
						obj.id = ids.length > 0 ? ids[0].id : '';
						submitData.push(obj);
						// 存储数据
						console.log(submitData);
					}
				}
			}
			if (!flag) {
				saveGroupPriority(submitData, this.checkGroup.userId)
					.then(res => {
						if (res.status === 200) {
							this.$message.success('保存技能分组成功！！！');
							this.getGroupWithUserIdInit();
							this.groupsSkill.isEdit = true;
						}
					})
					.catch(err => {
						if (err.code === '1301' && err.data.errCode === 1) {
							this.$message.error(`该技能组所属业务没有绑定AI工作流，请先为业务场景<${err.data.msg}>绑定AI工作流！`);
						} else if (err.code === '1105') {
							this.$message.error(`该账户无工作台权限无法进行操作`);
						} else {
							this.$message.error('保存技能分组失败！！！');
						}
						this.getGroupWithUserIdInit();
					});
				this.showBindGroup = false;
			}
		},
		// 增加技能组
		addGroupSkill() {
			let obj = {};
			obj = JSON.parse(JSON.stringify(this.defaultGroupSkill));
			this.groupsSkill.tableConent.push(obj);
		},

		// 删除分组
		removeGroupSkill(scope) {
			this.groupsSkill.tableConent.splice(scope.$index, 1);
		},

		// 编辑坐席属性
		async editProperty(index, row) {
			try {
				await checkWorkbench(row.userId);
				this.curAccount = row;
				this.schedulingAttributes = row.schedulingAttributes ? row.schedulingAttributes : [];
				this.showModifyProp = true;
			} catch (error) {
				if (error && error.code === '1105') {
					this.$message.error(`该账户无工作台权限无法进行操作`);
				}
			}
		},
		// 获取用户列表
		getAgentListInit() {
			this.$Spin.show();
			getUserList(this.checkAgent)
				.then(res => {
					if (res.status === 200) {
						this.checkAgent.total = res.data.data.count;
						const { data } = res.data.data;
						this.agentData.tableConent = data.map(item => {
							return {
								userId: item.id,
								userName: item.userName,
								fullName: item.fullName || '-',
								userOrg: item.org,
								status: item.isDisabled,
								isDisabled: item.isDisabled === 'N' ? '有效' : '失效',
								isRobot: item.isRobot,
								resetPwd: item.isRobot,
								userLevel: item.customerLevel,
								realName: item.profile.fullName,
								gender: item.profile.gender === 'male' ? '男' : '女',
								userPicture: item.profile.picture,
								schedulingAttributes: item.schedulingAttributes,
								role: item.user_role ? this.getRoleName(item.user_role.roleId) : '',
								roleId: item.user_role ? item.user_role.roleId : '',
								createdAt: item.createdAt ? this.$moment(item.createdAt).format('YYYY-MM-DD HH:mm:ss') : '-',
								permission: item.user_role ? this.getPermission(item.user_role.roleId) : [],
								originRole: item.role,
								isInitPwd: item.isInitPwd,
								initPwd: item.initPwd,
								createdBy: item.createdBy,
								isLockedByPasswordError: item.isLockedByPasswordError
							};
						});

						this.$Spin.hide();
					}
				})
				.catch(err => {
					console.error('get user list ', err);
					this.$Spin.hide();
					this.$requestApiError(err, () => {
						this.$router.push('/');
					});
				});
		},
		// 根据用户id获取绑定的分组
		getGroupWithUserIdInit() {
			getGroupWithUserId(this.checkGroup)
				.then(res => {
					this.checkGroup.total = res.data.count;
					console.log(res.data);
					const { data } = res.data;
					this.groupsSkillData = data;
					if (data.length > 0) {
						this.groupsSkill.tableConent = data.map(item => {
							return {
								name: {
									value: item.groupId,
									label: item.group.name,
									isRepeats: false,
									isEmpty: false,
									isSet: false
								},
								weight: {
									value: item.weight,
									isSet: false,
									invalid: false
								},
								isChief: {
									value: item.isChief !== 0,
									isSet: false,
									invalid: false
								},
								groupPriority: {
									value: item.groupPriority ? item.groupPriority : 1,
									isSet: false,
									invalid: false
								}
							};
						});
					}
				})
				.catch(err => {
					if (err.code === '1105') {
						this.$message.error(`该账户无工作台权限无法进行操作`);
					}
					this.$Spin.hide();
					this.$requestApiError(err, () => {
						this.$router.push('/');
					});
				});
		},
		// 失效坐席
		async stopEnableAgent(index, row, e) {
			console.log('去掉focus', e);
			let target = e.target;
			if (target.nodeName == 'SPAN') {
				target = e.target.parentNode;
			}
			target.blur();
			console.log('stopEnableAgent', row);
			try {
				const subtitle = `确定要${row.status === 'N' ? '停用' : '启用'}坐席 <${row.userName}> 吗, 是否继续?`;
				const isServingUser = await this.isServing(row.userId);
				console.log('isServingUser', isServingUser);
				if (isServingUser) {
					this.$confirm(`确定要停用坐席 <${row.userName}> 吗, 该坐席正在通话中，将会强制结束会话，是否继续?`, '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
						.then(async () => {
							await this.updateAccountInfo(row);

							this.$message({
								type: 'success',
								message: `${row.status === 'N' ? '停用' : '启用'}成功!`
							});
						})
						.catch(err => {
							console.log('err', err);
							this.$requestApiError(err, () => {
								this.$router.push('/');
							});
						});
				} else {
					this.$confirm(subtitle, '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
						.then(async () => {
							await this.updateAccountInfo(row);
							this.$message({
								type: 'success',
								message: `${row.status === 'N' ? '停用' : '启用'}成功!`
							});
						})
						.catch(err => {
							console.log('err', err);
							this.$requestApiError(err, () => {
								this.$router.push('/');
							});
						});
				}
			} catch (error) {
				console.error('stopEnableAgent Agent', error);
			}
		},
		// 变更角色
		changeRole(index, row) {
			this.curAccount = row;
			this.showChangeRole = true;
		},
		// 变更姓名
		changeName(index, row) {
			this.curAccount = row;
			this.showChangeName = true;
		},
		onAccountCreated() {
			this.showAddAgent = false;
			this.getAgentListInit();
		},
		// 属性更新
		updateAttributes() {
			this.showModifyProp = false;
			this.getAgentListInit();
			this.curAccount = {};
			this.schedulingAttributes = [];
		},
		async getRoleList() {
			this.roles = [];
			try {
				const res = await getRoleList();
				const { code, data } = res.data;
				if (code === 200 && data && data.length > 0) {
					data.map(item => {
						const { id, name, permissions, canSelect } = item;
						this.roles.push({ id, name, permissions, canSelect });
						if (id == this.userRoleId) {
							if (name === '机构管理员') {
								this.isOrgAdmin = true;
							} else {
								this.isOrgAdmin = false;
							}
						}
					});
					console.log('isOrgAdmin', this.isOrgAdmin);
				} else {
					console.warn('get role list  ', res);
				}
			} catch (error) {
				console.error('get role list error ', error);
			}
		},
		getPermission(roleId) {
			if (!roleId) {
				return [];
			}
			const roles = this.roles.find(item => item.id === roleId);
			if (!roles || !roles.permissions) {
				return [];
			}
			const permission = [];
			roles.permissions.map(item => {
				permission.push(item.resourceId);
			});
			return permission;
		},
		getRoleName(roleId) {
			if (!roleId) {
				return '';
			}

			const roles = this.roles.find(item => item.id === roleId);
			console.log('##r', roles, roleId, this.roles);

			if (!roles) {
				return '';
			}
			return roles.name || '';
		},
		onChangeRole() {
			this.showChangeRole = false;
			const self = this;
			setTimeout(() => {
				self.getAgentListInit();
			}, 1000);
		},
		/**
		 * 停用 /启用坐席账号
		 * @param { Object } row
		 */
		updateAccountInfo(row) {
			let params = [
				{ op: 'replace', path: '/isDisabled', value: row.status === 'N' ? 'Y' : 'N' } // 设置该用户是否失效   Y/停用  N/没有失效
			];
			let data = {};
			data.params = params;
			data.userId = row.userId;
			return new Promise((resolve, reject) => {
				updateAccountInfo(data)
					.then(res => {
						if (res.status === 200) {
							this.getAgentListInit();
							resolve('ok');
						}
					})
					.catch(err => {
						reject(err);
					});
			});
		},
		onShowBindLabelDialog(row) {
			this.showBindLabel = true;
			this.willBindBizLabelUserData = row;
		},
		onCloseBindLabelDialog() {
			this.showBindLabel = false;
		}
	}
};
</script>

<style lang="less">
.account {
	.header {
		padding: 20px 0;
		display: flex;
		justify-content: space-between;

		.label-wrapper {
			text-align: center;
		}

		.label {
			font-size: 12px;
			font-weight: 500;
			color: #6384fe;
			line-height: 24px;
		}

		.line {
			width: 76px;
			height: 2px;
			background: #6384fe;
			margin-top: 12px;
		}
		.btns {
			text-align: right;
			.import-account-button {
				width: 80px;
				height: 28px;
				background: #ffffff;
				border: 1px solid #8ed8a5;
				border-radius: 4px;
				font-size: 12px;
				font-weight: 400;
				color: #8ed8a5;
				line-height: 28px;
				padding: 0;
			}
			.account-button {
				width: 80px;
				height: 28px;
				background: #ffffff;
				border: 1px solid #6384fe;
				border-radius: 4px;
				font-size: 12px;
				font-weight: 400;
				color: #6384fe;
				line-height: 28px;
				padding: 0;
			}
		}
	}
	.el-avatar > img {
		width: 100%;
	}
	.blue {
		background-color: #6384fe;
		color: #ffffff;
	}
	.stop-enable-blue {
		.el-button {
			background-color: #6384fe;
			border-color: #c6e2ff;
			color: #fff;
		}
	}
	.stop-enable-blue :hover {
		color: #409eff;
		border-color: #c6e2ff;
		background-color: #ecf5ff;
	}
}
</style>
